package api

import (
	"github.com/gin-gonic/gin"

	"gitee.com/dn-jinmin/chatcms/internal/domain"
	"gitee.com/dn-jinmin/chatcms/internal/logic"
	"gitee.com/dn-jinmin/chatcms/internal/svc"
	"gitee.com/dn-jinmin/chatcms/pkg/httpx"
)

type AI struct {
	svcCtx *svc.ServiceContext
	aI     logic.AI
}

func NewAI(svcCtx *svc.ServiceContext, aI logic.AI) *AI {
	return &AI{
		svcCtx: svcCtx,
		aI:     aI,
	}
}

func (h *AI) InitRegister(engine *gin.Engine) {
	g := engine.Group("v1/ai")
	g.GET("/models", h.ModelList)
	g.POST("/chat", h.Chat)
}

func (h *AI) ModelList(ctx *gin.Context) {
	res, err := h.aI.ModelList(ctx.Request.Context())
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}

func (h *AI) Chat(ctx *gin.Context) {
	var req domain.AIChatReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	res, err := h.aI.Chat(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}
